<template>
  <view class="page">
    <view class="panel">
      <text class="title">预约服务</text>
        <view class="form">
        <!-- 配爬员ID由路由携带，不在UI展示 -->
          <view class="item">
            <text class="label">服务日期</text>
            <picker mode="date" :value="form.serviceDate" @change="e=>form.serviceDate=e.detail.value">
              <view class="picker">{{ form.serviceDate || '请选择日期' }}</view>
            </picker>
          </view>
        <view class="row times">
          <view class="item half">
            <text class="label">开始时间</text>
            <picker mode="time" :value="form.startTime" @change="e=>form.startTime=e.detail.value">
              <view class="picker large">{{ form.startTime || '选择开始' }}</view>
            </picker>
          </view>
          <view class="item half">
            <text class="label">结束时间</text>
            <picker mode="time" :value="form.endTime" @change="e=>form.endTime=e.detail.value">
              <view class="picker large">{{ form.endTime || '选择结束' }}</view>
            </picker>
          </view>
        </view>
        <view class="item">
          <text class="label">路线规划</text>
          <textarea class="textarea tall" v-model="form.routePlan" placeholder="路线规划详情"/>
        </view>
          <view class="row">
            <view class="item half">
              <text class="label">人数</text>
              <input class="input" type="number" v-model.number="form.participantCount"/>
            </view>
          <view class="item half">
            <text class="label">支付金额(¥)</text>
            <view class="amount">¥{{ calcAmount }}</view>
          </view>
          </view>
          <view class="row">
            <view class="item half">
              <text class="label">紧急联系人</text>
              <input class="input" v-model="form.emergencyContact"/>
            </view>
            <view class="item half">
              <text class="label">联系电话</text>
              <input class="input" v-model="form.emergencyPhone"/>
            </view>
          </view>
        <view class="item">
          <text class="label">备注</text>
          <textarea class="textarea" v-model="form.remark" placeholder="可选"/>
        </view>
        </view>
      </view>
    <view class="footer">
      <button class="btn" @tap="submit">提交预约</button>
    </view>
    </view>
    
  </template>
  
  <script>
  import { createOrder } from '@/api/order'
  import { getCoachDetail } from '@/api/coach'
  import store from '@/store'
  export default {
    data(){
      return {
        form: {
          climberId: '',
          userId: '',
          serviceDate: '',
          startTime: '',
          endTime: '',
          routePlan: '',
          participantCount: 1,
          paymentStatus: 'UNPAID',
          orderStatus: 'PENDING',
          emergencyContact: '',
          emergencyPhone: '',
        remark: ''
        },
        loading: false
      }
    },
    async onLoad(query){
      const uid = store.getters && store.getters.id
      if (uid) this.form.userId = uid
      if (query && (query.id || query.climberId)) this.form.climberId = query.id || query.climberId
      if (query && query.price) {
        this.form.price = Number(query.price)
      } else if (this.form.climberId) {
        // 如果未携带价格参数，则以陪爬员详情为准，避免价格不一致导致金额异常
        try {
          const res = await getCoachDetail(this.form.climberId)
          const data = res && res.data ? res.data : res
          if (data && (data.price != null)) this.form.price = Number(data.price)
        } catch(e) {}
      }
    },
  computed: {
    // 金额 = 价格 * 小时数，<0.5 按 0.5，>=0.5 且 <1 按 1
    calcAmount(){
      const start = this.form.startTime
      const end = this.form.endTime
      if (!start || !end) return 0
      const [sh, sm] = start.split(':').map(n=>Number(n))
      const [eh, em] = end.split(':').map(n=>Number(n))
      let minutes = (eh*60+em) - (sh*60+sm)
      if (minutes <= 0) return 0
      const hoursRaw = minutes / 60
      let billHours = 0
      if (hoursRaw <= 0.5) billHours = 0.5
      else if (hoursRaw < 1) billHours = 1
      else {
        const integer = Math.floor(hoursRaw)
        const frac = hoursRaw - integer
        if (frac === 0) billHours = integer
        else if (frac <= 0.5) billHours = integer + 0.5
        else billHours = integer + 1
      }
      const price = Number(this.form.price || 0)
      // 如果从详情页未传价格，可在进入本页时注入 price；否则金额为 0
      return Number((price * billHours).toFixed(2))
    }
  },
    methods: {
    
      async submit(){
        if (this.loading) return
        // 基础校验
        const f = this.form
      const requireFields = ['climberId','userId','serviceDate','startTime','endTime','participantCount','emergencyContact','emergencyPhone']
        for (const k of requireFields) {
          if (f[k] === '' || f[k] === null || f[k] === undefined) {
            this.$modal && this.$modal.showToast('请完善必填项')
            return
          }
        }
        this.loading = true
        try {
        const res = await createOrder({
            climberId: Number(f.climberId),
            userId: Number(f.userId),
            serviceDate: f.serviceDate,
            startTime: f.startTime,
            endTime: f.endTime,
            routePlan: f.routePlan,
            participantCount: Number(f.participantCount||1),
          amount: Number(this.calcAmount||0),
            paymentStatus: f.paymentStatus,
            orderStatus: f.orderStatus,
            emergencyContact: f.emergencyContact,
            emergencyPhone: f.emergencyPhone,
          remark: f.remark
          })
        if ((res && res.code) === 200) {
          this.$modal && this.$modal.showToast('提交成功，订单状态：待接单；后续消息请关注消息中心')
          setTimeout(()=>{ uni.navigateBack() }, 1000)
        }
        } finally {
          this.loading = false
        }
      }
    }
  }
  </script>
  
  <style scoped>
  .page { padding: 16rpx 16rpx 140rpx 16rpx; }
.panel { background:#fff; border-radius: 16rpx; box-shadow: 0 8rpx 24rpx rgba(0,0,0,.06); padding: 20rpx; }
  .title { font-size: 32rpx; font-weight: 700; margin-bottom: 12rpx; }
  .form { display:block; }
.item { margin-bottom: 18rpx; }
  .row { display:flex; gap: 12rpx; }
.times .picker.large { padding: 18rpx 16rpx; font-size: 28rpx; }
  .half { flex:1; }
  .label { display:block; color:#6b7280; font-size: 24rpx; margin-bottom: 6rpx; }
.input, .picker, .textarea { background:#f5f6f7; border-radius: 12rpx; padding: 16rpx 18rpx; }
.textarea { min-height: 180rpx; }
.textarea.tall { min-height: 240rpx; }
.amount { background:#ecfeff; color:#0ea5a5; border-radius: 12rpx; padding: 16rpx 18rpx; font-weight: 700; }
  .footer { position: fixed; left:0; right:0; bottom:0; background:#fff; box-shadow: 0 -8rpx 24rpx rgba(0,0,0,.06); padding: 12rpx 16rpx; }
  .btn { width: 100%; background:#0ea5a5; color:#fff; border:none; }
  </style>
  
  
  